<!-- 科室角色管理 -->
<template>
    <div class="department" v-loading="loading">
        <div class="tablename">
            科室/角色管理
            <!-- <SvgIcon name="/src/assets/logo-mini.svg" color="red" :size="30" /> -->
        </div>
        <div style="display: flex;width: 100%;">
            <div class="boxfafk1">
                <!-- 搜索框 -->
                <div>
                    <el-input size="default" clearable placeholder="科室" prefix-icon="Search" v-model="searchBox" />
                </div>
                <!-- 科室管理 -->
                <div>
                    <div>
                        <el-tree ref="tree" :data="departmentArr" node-key="id" default-expand-all :props="defaultProps"
                            :filter-node-method="filterNode" :expand-on-click-node="false" :default-checked-keys="[1]"
                            @node-click="handleNodeClick">
                            <template #default="{ node, data }">
                                <div class="custom-tree-node">
                                    <span v-if="data.department_name.length <= 10">{{ data.department_name }}</span>
                                    <el-popover style="cursor: pointer;" size="small" v-else placement="top-start"
                                        width="200" trigger="hover" :content="data.department_name">
                                        <template #reference>
                                            <span>{{ data.department_name.substring(0, 10) + '...' }}</span>
                                        </template>

                                    </el-popover>
                                    <!-- <span>{{ data.department_name }}</span> -->
                                    <el-dropdown v-bind:class="{ selected: data.id == currentdepart.id }"
                                        class="dropdown" placement="bottom-end" trigger="click">
                                        <div style="width: 20px;text-align: center">
                                            <!-- ... -->
                                            <SvgIcon name="/src/assets/img/svg/el-icon-more2.svg" />
                                        </div>
                                        <template #dropdown>
                                            <el-dropdown-menu>
                                                <el-dropdown-item :disabled="item.disabled"
                                                    v-for="(item, index) in depart_opbutton"
                                                    @click.native="departmentop(item.prop, data)" :key="index">
                                                    {{ item.label }}
                                                </el-dropdown-item>
                                            </el-dropdown-menu>
                                        </template>
                                    </el-dropdown>
                                </div>
                            </template>
                        </el-tree>
                    </div>
                </div>
                <!-- 科室管理 -->
            </div>

            <!-- 角色管理 -->
            <div style="width: 100%;margin-top: 10px;">
                <!-- 角色表格栏 -->
                <dy-table :elTable_Options="elTable_Options" @handleClick="handleClick" @bottonHandle="bottonHandle"
                    ref="table" />
            </div>
        </div>
        <div style="height: 50px;"></div>
        <!-- 操作科室弹框 -->
        <OpearDP ref="myopearDepartment" @cbhandle="opearBC" v-if="modalStatus == '操作科室弹框'" />
        <!-- 操作角色弹框 -->
        <OpearRole ref="myopearRole" @cbhandle="opearBC" v-if="modalStatus == '角色操作弹框'" />
    </div>
</template>

<script setup>
import { reactive, ref, toRefs, computed, onMounted, watch, nextTick } from 'vue'
import { useCach } from '@/store/cach'
import { ElMessageBox, ElMessage } from 'element-plus'
import { useRouter } from 'vue-router'
import api from '@/api'
import commonV from '@/common'
//组件
import OpearDP from './departmentMan/opearDepartment.vue'
import OpearRole from './departmentMan/opearRole.vue'

const router = useRouter()

let pageConfig = useCach()
let departmentRoles = computed(() => pageConfig.departmentRoles)
let modalStatus = computed(() => pageConfig.modalStatus)

let state = reactive({
    loading: false,
    searchBox: '',
    departmentArr: [],
    defaultProps: {
        children: "children",
        label: "department_name"
    },
    currentdepart: {},
    depart_opbutton: [{
        label: "添加子部门",
        prop: 'add'
    }, {
        label: "修改信息",
        prop: 'edit'
    }, {
        label: "删除",
        prop: 'delete'
    }]
})
let {
    loading, searchBox,
    departmentArr, defaultProps,
    currentdepart, depart_opbutton
} = toRefs(state)

//表格数据
let elTable_Options = reactive({
    selection: false, //多选
    //获取方法
    getwayname: "roles",
    name: "departmentMan", //标识
    addConditions: [{
        key: "department",
        value: ""
    }],
    opbutton: [{
        label: "添加角色",
        dealway: "addrole",
        icon: 'Plus',
        type: "primary"
    }],
    //列表表头
    eltableArr: [{
        label: "角色名称",
        prop: "role_name",
        columType: 'linkTo',
        index: 3,
    },
    {
        label: "描述",
        prop: "description",
        columType: 'text'
    },
    {
        label: "备注",
        prop: "remark",
        columType: 'text'
    }, {
        label: "操作",
        prop: "",
        width: 200,
        columType: 'opreatebar',
        operation: [{
            op_name: "编辑",
            op_index: "4",
            color: "#20A0FF"
        }, {
            op_name: "权限",
            op_index: "6",
            color: "#F7BA2A"
        }, {
            op_name: "人员",
            op_index: "7",
            color: "#67C23A"
        }, {
            op_name: "删除",
            op_index: "5",
            color: "#FF4949"
        }]
    }],
    //查询栏
    searchList: [{
        label: "角色名称",
        key: "role_name",
        searchtype: 'input'
    }]
})

//实例
let table = ref(null)
let tree = ref(null)
let myopearDepartment = ref(null)
let myopearRole = ref(null)

onMounted(() => {
    getdepartdata()
})

watch(() => state.searchBox, val => {
    tree.value.filter(val)
})

//获取科室信息
let getdepartdata = async () => {
    state.loading = true
    let params = {}
    if (state.searchBox) {
        params.search = state.searchBox
    }
    let res = await api.getaxiosdata('department', params)
    if (res) {
        state.departmentArr = commonV.transDatatotree(res, "id", "parent_id", "children") //将普通数组转换为tree数组
        if (res.length) {
            nextTick(function () {
                //Dom更新完毕
                let row = departmentRoles.value ? JSON.parse(JSON.stringify(departmentRoles.value)) : null
                if (row) {
                    //从人员页面回来
                    state.currentdepart = JSON.parse(JSON.stringify(row))
                    tree.value.setCurrentKey(state.currentdepart.id)
                    //加载角色信息
                    handleNodeClick(state.currentdepart)
                    pageConfig.update_departmentRoles(null)

                } else {
                    let currentdepart = res[0]
                    if (JSON.stringify(state.currentdepart) != "{}") {
                        currentdepart = state.currentdepart
                    }
                    try {
                        tree.value.setCurrentKey(currentdepart.id)
                        //加载角色信息
                        handleNodeClick(currentdepart)
                    } catch (error) { }
                }
            })
        }
    }
    state.loading = false
}

//过滤结构树
let filterNode = (value, data) => {
    if (!value) return true
    return data.department_name.indexOf(value) !== -1
}

//科室节点点击
let handleNodeClick = (data) => {
    state.currentdepart = data
    elTable_Options.addConditions = [{
        key: "department",
        value: data.id
    }]
    // this.$refs.myeltable.$refs.queryBar.searchBox = {} //切换时清空角色搜索框
    gettabledata()
}

//获取角色列表
let gettabledata = (row) => {
    nextTick(() => {
        table.value.getTableData(row)
    })
}

//科室操作
let departmentop = (type, row) => {
    //add：添加子部门 edit：修改名称 delete：删除
    if (type == 'add' || type == 'edit') {
        pageConfig.changeShowModal(true)
        pageConfig.changeModalStatus('操作科室弹框')
        let params = {}
        params.type = type
        params.departmentRow = row
        nextTick(() => {
            myopearDepartment.value.openFunction(params)
        })
    } else if (type == 'delete') {
        //先判断底下是否有人员信息再删除
        if (typeof row.children == "undefined" || row.children == null) {
            row.children = []
        }
        if (typeof row.department == "undefined" || row.department == null) {
            row.department = []
        }
        if (row.children.length || row.department.length) {
            ElMessage({
                message: "该科室下有子科室或人员，无法删除",
                type: "warning"
            })
        } else {
            state.currentdepart = {}
            ElMessageBox.confirm('确定删除?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(async () => {
                state.loading = true
                let res = await api.changeaxiosdata('department', 'delete', { id: row.id })
                if (res != null) {
                    ElMessage({
                        message: "删除成功",
                        type: "success"
                    })
                    getdepartdata()
                }
                state.loading = false
            }).catch(() => { })
        }
    }
}

//操作回调
let opearBC = (type = 'department') => {
    //重新获取数据
    if (type == 'department') {
        getdepartdata()
    }
    handleNodeClick(state.currentdepart)
}

//table 点击事件
let handleClick = (row, index) => {
    console.log(index)
    if (index == '4') {
        //编辑角色
        pageConfig.changeShowModal(true)
        pageConfig.changeModalStatus('角色操作弹框')
        let params = {
            type: 'edit',
            departmentId: state.currentdepart.id,
            roleRow: row
        }
        nextTick(() => {
            myopearRole.value.openFunction(params)
        })
    } else if (index == '5') {
        //删除
        ElMessageBox.confirm("确定删除该角色?", "提示", {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning"
        }).then(async () => {
            state.loading = true
            await api.changeaxiosdata('roles', 'delete', { id: row.id })
            ElMessage({
                message: '操作成功!',
                type: 'success'
            })
            handleNodeClick(state.currentdepart)
            state.loading = false
        }).catch(() => { })
    } else if (index == '7') {
        //查看人员
        pageConfig.update_departmentRoles(state.currentdepart)
        router.push({
            path: '/systemManage/departmentMan/users',
            query: {
                id: row.id,
                name: row.role_name
            }
        })
    } else if (index == '6') {
        //权限
        pageConfig.update_departmentRoles(state.currentdepart)
        router.push({
            path: '/systemManage/sysmenuManagement',
            query: {
                id: row.id
            }
        })
    }
}

//table 按钮点击事件
let bottonHandle = (wayname) => {
    if (wayname == 'addrole') {
        pageConfig.changeShowModal(true)
        pageConfig.changeModalStatus('角色操作弹框')
        let params = {
            type: 'add',
            departmentId: state.currentdepart.id
        }
        nextTick(() => {
            myopearRole.value.openFunction(params)
        })
    }
}
</script>

<style lang="scss" scoped>
.department {
    width: 100%;
    height: 100%;
    overflow-y: auto;
    background: rgba(255, 255, 255, 1);
    border-radius: 2px;
    box-shadow: 0px 0px 4px 0px rgba(0, 0, 0, 0.1);
    border-left: none;
    border-right: none;
    margin-top: 10px;
}

.tablename {
    font-size: 18px;
    color: #1f2d3d;
    padding: 16px 20px 10px;
}

.boxfafk1 {
    width: 400px;
    min-width: 300px;
    margin-right: 20px;
    height: 675px;
    margin-top: 10px;
    border: 1px solid rgba(211, 220, 230, 1);
    overflow-y: auto;
    padding-bottom: 10px;

    &:deep(.el-input__inner) {
        border: none;
        border-bottom: 1px solid #dcdfe6;
        border-radius: 0;
    }

    &:deep(.el-input__prefix) {
        height: 8%
    }

    &:deep(.el-tree-node__content :hover>.dropdown) {
        visibility: visible;
    }

    &:deep(.el-tree-node.is-current>.el-tree-node__content>.dropdown) {
        visibility: visible !important;
        color: #ffffff;
    }

    &:deep(.custom-tree-node) {
        width: 100%;
        display: flex;
        justify-content: space-between;
        padding-right: 10px;
    }

    &:deep(.el-tree-node.is-current>.el-tree-node__content) {
        background-color: #20a0ff !important;
        color: #ffffff;
    }

    &:deep(.el-input__wrapper) {
        box-shadow: none;
    }
}

.elTable {
    /* margin-top: 10px; */
    background: rgba(255, 255, 255, 1);
    box-shadow: 0px 0px 4px 0px rgba(0, 0, 0, 0.1);
    border-radius: 2px;
    padding: 16px 20px;
}

.tablename {
    display: flex;
    justify-content: space-between;
    align-content: center;
    margin-bottom: 10px;
    font-size: 18px;
    color: #1f2d3d;
}

.dropdown {
    visibility: hidden;
}

.selected {
    visibility: visible !important;
}
</style>